package async;

import java.io.IOException;
import java.nio.ByteBuffer;

import com.google.protobuf.CodedOutputStream;
import com.google.protobuf.Message;

public class MessageSerializer {

	public ByteBuffer serilize(Message message) throws IOException {
		
		//prepare buffer
		int messagelength = message.getSerializedSize();
		int prefixLength = CodedOutputStream.computeRawVarint32Size(messagelength);
		int totalLength = messagelength +  prefixLength;
		byte[] buf = new byte[totalLength];
		
		//write length
		CodedOutputStream cos = CodedOutputStream.newInstance(buf);
		cos.writeRawVarint32(messagelength);
		cos.flush();
		
		//write buffer
		ByteBuffer b = ByteBuffer.wrap(buf);
		b.position(prefixLength);
		b.put(message.toByteArray());
		b.flip();

		return b;
	}
	
}
